//
//  DetailViewController.m
//  Comma
//
//  Created by 张诗雨 on 15/1/23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//


#import "OtherPersonViewController.h"
#import "WeiboSDK.h"
#import "DetailViewController.h"
#import "DetailView.h"
#import "GlobalMethod.h"
#import "AFNetWorkingYU.h"
#import "DetailModel.h"
#import "URLMacro.h"
#import "DetailReplyTableViewCell.h"
#import "DetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "AFHTTPSessionManager.h"
#import "ExpressionView.h"
#import "MJRefresh.h"
#import "MJRefreshHeaderView.h"
#import "LoadIndicator.h"
#import "YRSideViewController.h"
#import "OtherModel.h"
#import "SETextView.h"
#import "FaceModel.h"
#import "EditImage.h"
@interface DetailViewController ()<UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, DetailReplyTableViewCellDelegate, DetailTableViewCellDelegate, ExpressionViewDelegate, SETextViewDelegate>

@end

@implementation DetailViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArray = [NSMutableArray array];
        self.cellHeight = [NSMutableArray array];
        self.page = 2;
        //        self.load = [[LoadIndicator alloc] init];
    }
    return self;
}
- (void)viewDidAppear:(BOOL)animated
{
    //    [LoadIndicator stopAnimationInView:self.customView];
    //    [self.load stopAnimationLoadView];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    //    [LoadIndicator addIndicatorInView:self.customView];
    //    [self.load addLoadView:self.customView];
    YRSideViewController *slide = [YRSideViewController share];
    slide.needSwipeShowMenu = NO;
}
- (void)loadView
{
    [super loadView];
    
    self.customView = [[DetailView alloc] initWithLeftButton:@"返回" RightButton:nil Title:nil FooterView:FooterViewStateCustom];
    self.view = _customView;
    [self.customView createTableHeaderView];
    [self.customView createTableView];
    [self.customView.commentTabelView setTableHeaderView:self.customView.tableHeaderView];
    [self.customView.commentTabelView setDataSource:self];
    [self.customView.commentTabelView setDelegate:self];
    [self.customView.commentTabelView registerClass:[DetailTableViewCell class] forCellReuseIdentifier:@"detailCell"];
    [self.customView.commentTabelView registerClass:[DetailReplyTableViewCell class] forCellReuseIdentifier:@"detailReplyCell"];
    [self.customView createShare];
    if ([[self.otherDic objectForKey:@"good"] isEqual:@(NO)]){
        [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise"] forState:UIControlStateNormal];
        
    }else if ([[self.otherDic objectForKey:@"good"] isEqual:@(YES)]){
        [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise_effect"] forState:UIControlStateNormal];
        
    }
    if ([[self.otherDic objectForKey:@"bad"] isEqual:@(NO)]){
        [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle"] forState:UIControlStateNormal];
        
    }else if ([[self.otherDic objectForKey:@"bad"] isEqual:@(YES)]){
        [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle_effect"] forState:UIControlStateNormal];
    }
    [self addButtonAction];
    [self.customView.expressionView setDelegate:self];
    //  刷新表格
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (ino64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.customView.commentTabelView reloadData];
        [self.customView.commentTabelView headerBeginRefreshing];
    });
    [self.customView.writeTextField setDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    //    [self requestCommentData];
    [self requsetData];
    [self addheaderView];
    [self addFooterRefresh];
    
}

#pragma mark - 按钮点击事件
// 赞的点击事件
- (void)supportButtonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CONNECT" object:self];
    [self.customView.supportButton setEnabled:NO];
    [self.customView.demeanButton setEnabled:NO];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userId = [user objectForKey:@"id"];
    NSString *approveKey= [GlobalMethod GetIOSUUID];
    NSString *deviceParam = [GlobalMethod getApproveKey];
    NSString *infoId = self.model.id;
    NSString *body = [NSString stringWithFormat:@"infoId=%@&approveKey=%@&deviceParam=%@", infoId, approveKey, deviceParam];
    [AFNetWorkingYU netWorkWithURL:URL_ISUSO_GOOD body:body resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            [self.customView.supportButton setEnabled:YES];
            [self.customView.demeanButton setEnabled:YES];
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:result];
            NSString *str = [dic objectForKey:@"msg"];
            //            [self aleareViewWithString:str];
            if ([str isEqualToString:@"点赞成功"]) {
                [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise_effect"] forState:UIControlStateNormal];
                //                [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle"] forState:UIControlStateNormal];
                NSInteger value = [self.customView.goodLable.text longLongValue];
                value++;
                self.customView.goodLable.text = [NSString stringWithFormat:@"%ld", value];
                
            } else if([str isEqualToString:@"取消成功"]) {
                [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise"] forState:UIControlStateNormal];
                NSInteger value = [self.customView.goodLable.text longLongValue];
                value--;
                self.customView.goodLable.text = [NSString stringWithFormat:@"%ld", value];
                
                //                [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle"] forState:UIControlStateNormal];
                //     NSLog(@"取消成功");
            }
        }
        else
        {
            [self aleareViewWithString:@"操作失败"];
        }
        
    }];
    
}
// 踩的点击事件
- (void)demeanButtonAction:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CONNECT" object:self];
    
    [self.customView.supportButton setEnabled:NO];
    [self.customView.demeanButton setEnabled:NO];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    //    NSString *userId = [user objectForKey:@"id"];
    NSString *approveKey= [GlobalMethod GetIOSUUID];
    NSString *deviceParam = [GlobalMethod getApproveKey];
    NSString *infoId = self.model.id;
    NSString *body = [NSString stringWithFormat:@"infoId=%@&approveKey=%@&deviceParam=%@", infoId, approveKey, deviceParam];
    [AFNetWorkingYU netWorkWithURL:URL_ISUSO_BAD body:body resultBlock:^(id result) {
        [self.customView.supportButton setEnabled:YES];
        [self.customView.demeanButton setEnabled:YES];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:result];
            NSString *str = [dic objectForKey:@"msg"];
            if ([str isEqualToString:@"点赞成功"]) {
                //                 [self aleareViewWithString:@"踩成功"];
                [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle_effect"] forState:UIControlStateNormal];
                NSInteger value = [self.customView.badLable.text longLongValue];
                value++;
                self.customView.badLable.text = [NSString stringWithFormat:@"%ld", value];
                //                 [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise"] forState:UIControlStateNormal];
            } else if([str isEqualToString:@"取消成功"]) {
                [self.customView.demeanButton setBackgroundImage:[UIImage imageNamed:@"Button_Belittle"] forState:UIControlStateNormal];
                NSInteger value = [self.customView.badLable.text longLongValue];
                value--;
                self.customView.badLable.text = [NSString stringWithFormat:@"%ld", value];
                //                                  [self.customView.supportButton setBackgroundImage:[UIImage imageNamed:@"Button_Praise"] forState:UIControlStateNormal];
            }
        }
        else
        {
            [self aleareViewWithString:@"操作失败"];
        }
    }
     
     ];
}

// 分享的点击事件
- (void)shareButtonAction:(id)sender
{
    [UIView animateWithDuration:0.12 animations:^{
        self.customView.shareView.frame = CGRectMake(0, SCREEN_HEIGHT - self.customView.shareView.frame.size.height, SCREEN_WIDTH, self.customView.shareView.frame.size.height);
        self.customView.shareButton.transform = CGAffineTransformMakeRotation(45 *M_PI / 180.0);
        self.customView.shareButton.hidden = YES;
    } completion:^(BOOL finished) {
        [self.customView bringSubviewToFront:self.customView.shareView];
        //        [self.customView bringSubviewToFront:self.customView.shareButton];
    }];
}
// 表情键盘
- (void)senderButtonAction:(id)sender
{
    
    //    self.customView.writeTextField.
    
    
    NSString * content = [NSString stringWithFormat:@"%@", self.resultStr];
    NSString *approveKey = [GlobalMethod GetIOSUUID];
    NSString *deviceParam = [GlobalMethod getApproveKey];
    NSString * body = [NSString stringWithFormat:@"approveKey=%@&deviceParam=%@&infoId=%@&title=%@&content=%@", approveKey, deviceParam, self.model.id, self.model.title, content];
    [AFNetWorkingYU netWorkWithURL:URL_PUB_MSG body:body resultBlock:^(id result) {
        //        NSLog(@"%@", result);
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSString *msg = [result objectForKey:@"msg"];
            [self aleareViewWithString:msg];
            [self.customView.writeTextField setDelegate:self];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (ino64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.customView.commentTabelView reloadData];
                [self.customView.commentTabelView headerBeginRefreshing];
            });
        }
        else {
            [self aleareViewWithString:@"未知错误"];
        }
        
    }];
    [self.customView.writeTextField endEditing:YES];
    [UIView animateWithDuration:0.3 animations:^{
        [self.customView.writeView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
        [self.customView.expressionView setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, self.customView.expressionView.frame.size.height)];
    } completion:^(BOOL finished) {
        
    }];
    
}
- (void)leftButtonAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 按钮点击事件结束

#pragma mark - 表情
- (void)expressionViewReturn:(NSDictionary *)infoDic
{
    
    EditImage *myImage = [[EditImage alloc] initWithData:[infoDic objectForKey:@"imaData"]];
    myImage.name = [infoDic objectForKey:@"code"];
    [self.customView.writeTextField insertObject:myImage size:CGSizeMake(20, 20)];
}

-(void)editTextFinishedValue:(NSString *)endValue
{
    self.resultStr = endValue;
}

- (void)textViewDidChange:(SETextView *)textView
{
    [self updateLayout];
}


- (void)updateLayout
{
    BOOL change = NO;
    
    CGSize containerSize = self.customView.scrollView.frame.size;
    CGSize contentSize = [self.customView.writeTextField sizeThatFits:containerSize];
    
    CGRect frame = self.customView.writeTextField.frame;
    frame.size.height = MAX(contentSize.height, containerSize.height);
    
    self.customView.writeTextField.frame = frame;
    self.customView.scrollView.contentSize = frame.size;
    
    
    
    if (self.customView.beforeHeight == frame.size.height) {
        change = NO;
        [self.customView.scrollView scrollRectToVisible:self.customView.writeTextField.caretRect animated:YES];
    } else {
        self.customView.beforeHeight = frame.size.height;
        change = YES;
    }
    
    
    if (frame.size.height < 100 && frame.size.height > 32 && change) {
        
        
        [self.customView.writeView setFrame:CGRectMake(self.customView.writeView.frame.origin.x, self.customView.writeView.frame.origin.y - self.customView.beforeHeight + self.customView.scrollView.frame.size.height, self.customView.writeView.frame.size.width, self.customView.writeView.frame.size.height + self.customView.beforeHeight - self.customView.scrollView.frame.size.height)];
        self.customView.scrollView.frame = CGRectMake(self.customView.scrollView.frame.origin.x, self.customView.scrollView.frame.origin.y, self.customView.scrollView.frame.size.width, frame.size.height);
        self.customView.writeTextField.frame = CGRectMake(self.customView.writeTextField.frame.origin.x, 0, self.customView.scrollView.frame.size.width, self.customView.scrollView.frame.size.height);
    }
    
    
    
}
//    [self.customView.writeTextField setText:[NSString stringWithFormat:@"%@%@", self.customView.writeTextField.text, [infoDic objectForKey:@"code"]]];}
#pragma mark - 网络请求
- (void)requsetData
{
    
    NSString *str = [NSString stringWithFormat:@"%@?id=%@", URL_GET_INFO, self.model.id];
    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
        if ([result isKindOfClass:[NSDictionary class]]) {
            
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary:result];
            if ([[dic objectForKey:@"msg"] isEqualToString:@"获取成功"]) {
                NSDictionary *myDic = [dic objectForKey:@"obj"];
                self.model = [[DetailModel alloc] initWithDictionary:myDic];
                [self data];
            } else {
                [self aleareViewWithString:[dic objectForKey:@"msg"]];
            }
        } else {
#warning <<<
        }
    }];
}
//- (void)requestCommentData
//{
//    self.page = 1;
//#warning rid需要更改
//    NSString * str = [NSString stringWithFormat:@"%@?page=%ld&rows=%@&sort=pub_time&order=desc&rid=%@",URL_GET_MSG_INFO, self.page, @"10", self.model.id];
//
//    [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
//        if ([result isKindOfClass:[NSDictionary class]]) {
//            [self.dataArray removeAllObjects];
//        NSDictionary * resultDic = [[NSDictionary dictionaryWithDictionary:result] objectForKey:@"rows"];
//        for (NSDictionary * element in resultDic) {
//            [self.dataArray addObject:element];
//        }
//            [self.customView.commentTabelView reloadData];
////        [self data];
//        } else {
//#warning <<<
//        }
//    }];
//}

- (void)addheaderView
{
    [self.customView.commentTabelView addHeaderWithCallback:^{
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        
        NSString *userId = [user objectForKey:@"id"];
        
        NSString *str = [NSString stringWithFormat:@"%@?id=%@", URL_GET_INFO, self.model.id];
        
        [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSDictionary *dic = [NSDictionary dictionaryWithDictionary:result];
                self.model = [[DetailModel alloc] initWithDictionary:[dic objectForKey:@"obj"]];
                self.customView.contentView.delegate = self;
                [self data];
            }
            else {
#warning <<<
            }
        }];
        
        self.page = 2;
        
        NSString * str1 = [NSString stringWithFormat:@"%@?page=0&rows=%@&sort=pub_time&order=desc&rid=%@",URL_GET_MSG_INFO, @"10", self.model.id];
        [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str1 resultBlock:^(id result) {
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSArray * resultDic = [[NSDictionary dictionaryWithDictionary:result] objectForKey:@"rows"];
                if ([resultDic count] > 0) {
                    [self.dataArray removeAllObjects];
                }
                for (NSDictionary * element in resultDic) {
                    [self.dataArray addObject:element];
                }
            } else {
#warning <<<
            }
            [self.customView.commentTabelView reloadData];
        }];
        [self.customView.commentTabelView headerEndRefreshing];
        
    }];
    
}
- (void)addFooterRefresh
{
    [self.customView.commentTabelView addFooterWithCallback:^{
        
        
        if (self.page < 10) {
            
            
            NSString * str = [NSString stringWithFormat:@"%@?page=%d&rows=%@&sort=pub_time&order=desc&rid=%@",URL_GET_MSG_INFO, self.page, @"10", self.model.id];
            [AFNetWorkingYU netWorkingHanderGetGataWithUrl:str resultBlock:^(id result) {
                if ([result isKindOfClass:[NSDictionary class]]) {
                    NSDictionary * resultDic = [[NSDictionary dictionaryWithDictionary:result] objectForKey:@"rows"];
                    for (NSDictionary * element in resultDic) {
                        [self.dataArray addObject:element];
                    }                        //        [self data];
                } else {
#warning <<<
                }
                [self.customView.commentTabelView reloadData];
            }];
            [self.customView.commentTabelView footerEndRefreshing];
            
            self.page++;
        }
    }];
}
//赋值
- (void)data
{
    //分类
    self.customView.typeLable.text = [NSString stringWithFormat:@"%@ • ", self.model.category];
    //头像
    NSString *imgStr = [NSString stringWithFormat:@"%@%@",@"http://www.isu.so/attached/u_img/", self.model.puberImg];
    NSURL *imgUrl = [NSURL URLWithString:imgStr];
    [self.customView.headPic sd_setImageWithURL:imgUrl];
    
#pragma - 给头像添加手势跳转个人中心
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:)];
    tapGes.numberOfTapsRequired = 1; // 单击
    [self.customView.headPic addGestureRecognizer:tapGes];
    //标题
    self.customView.titleLable.text = self.model.title;
    self.customView.titleLable.frame = CGRectMake(self.customView.typeLable.frame.origin.x + self.customView.typeLable.frame.size.width, self.customView.typeLable.frame.origin.y, self.customView.frame.size.width - self.customView.typeLable.frame.origin.x - self.customView.typeLable.frame.size.width, self.customView.typeLable.frame.size.height);
    //    [self.customView.titleLable sizeToFit];
    if (self.customView.titleLable.frame.size.height > 33) {
        [self.customView.titleLable setTextAlignment:NSTextAlignmentLeft];
    }
    self.customView.titleLable.frame = CGRectMake(self.customView.typeLable.frame.origin.x + self.customView.typeLable.frame.size.width, self.customView.typeLable.frame.origin.y, self.customView.titleLable.frame.size.width - 30, self.customView.typeLable.frame.size.height);
    //发布者
    self.customView.puberNick.text = self.model.puberNick;
    [self.customView.puberNick setFrame:CGRectMake(self.customView.typeLable.frame.origin.x, 48, 0, 0)];
    [self.customView.puberNick sizeToFit];
    self.customView.dian.text = @" ";
    [self.customView.dian sizeToFit];
    [self.customView.dian setFrame:CGRectMake(self.customView.puberNick.frame.origin.x  + self.customView.puberNick.frame.size.width, 48, self.customView.dian.frame.size.width, self.customView.dian.frame.size.height)];
    //发布者信息
    NSString *puberRole = [self puberNickChangeString:self.model.puberRole];
    self.customView.puberRole.text = [NSString stringWithFormat:@"%@ • %@",puberRole, self.model.puberSchool];
    [self.customView.puberRole setFrame:CGRectMake(self.customView.typeLable.frame.origin.x + self.customView.puberNick.frame.size.width + self.customView.dian.frame.size.width, 48, 0, 0)];
    [self.customView.puberRole sizeToFit];
    
    //    if ((self.customView.pubTime.frame.size.width + self.customView.puberRole.frame.size.width + self.customView.puberRole.frame.origin.x ) > SCREEN_WIDTH) {
    //        self.customView.puberRole.numberOfLines = 2;
    //    [self.customView.puberRole setFrame:CGRectMake(self.customView.typeLable.frame.origin.x + self.customView.puberNick.frame.size.width, 48,SCREEN_WIDTH - self.customView.pubTime.frame.size.width - self.customView.typeLable.frame.origin.x - self.customView.puberNick.frame.size.width  - 8, self.customView.pubTime.frame.size.height * 2)];
    //    }
    
    [self.customView lineView:CGPointMake(5,  self.customView.puberRole.frame.origin.y + self.customView.puberRole.frame.size.height + 5) view:self.customView.tableHeaderView];
    
    //发布时间
    self.customView.pubTime.text = self.model.pubTime;
    [self.customView.pubTime sizeToFit];
    [self.customView.pubTime setFrame:CGRectMake(SCREEN_WIDTH - 8 - self.customView.pubTime.frame.size.width, self.customView.puberRole.frame.origin.y + self.customView.puberRole.frame.size.height + 10, self.customView.pubTime.frame.size.width, self.customView.pubTime.frame.size.height)];
    
    //内容详情
    [self.customView.contentView setFrame:CGRectMake(self.customView.typeLable.frame.origin.x, self.customView.puberRole.frame.origin.y + self.customView.puberRole.frame.size.height + self.customView.pubTime.frame.size.height + 17, SCREEN_WIDTH - self.customView.typeLable.frame.origin.x - 24, 10)];
    NSString *str = [NSString stringWithFormat:@"<p>%@</p>", self.model.content];
    self.customView.contentView.delegate = self;
    [self.customView.contentView loadHTMLString:str baseURL:nil];
    
    // 重新设定headerView
    //    NSTimer * timer = [NSTimer timerWithTimeInterval:1.5 target:self selector:@selector(refreshView) userInfo:nil repeats:NO];
    //    [timer fire];
}


-(void)SingleTap:(UITapGestureRecognizer*)recognizer
{
    OtherPersonViewController *otherVC = [[OtherPersonViewController alloc] init];
    otherVC.puberId = self.model.puberId;
    [self.navigationController pushViewController:otherVC animated:YES];
    
}
//网页加载完毕
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //网页自适应高度
    CGRect frame = self.customView.contentView.frame;
    CGSize fittingSize = [self.customView.contentView sizeThatFits:CGSizeMake((SCREEN_WIDTH - 96), 10000)];
    frame.size = fittingSize;
    NSString *str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",260];
    [self.customView.contentView stringByEvaluatingJavaScriptFromString:str];
    self.customView.contentView.frame = frame;
    [self.customView.contentView sizeToFit];
    //    [self.customView lineView:CGPointMake(5, self.customView.contentView.frame.origin.y + self.customView.contentView.frame.size.height + 5) view:self.customView.tableHeaderView];
    // 踩与赞
    [self.customView.goodImageView setFrame:CGRectMake(24, self.customView.contentView.frame.origin.y + self.customView.contentView.frame.size.height + 10, 11, 16)];
    self.customView.goodLable.text = [NSString stringWithFormat:@"%ld",[self.model.good longValue]];
    [self.customView.goodLable setFrame:CGRectMake(self.customView.goodImageView.frame.origin.x + self.customView.goodImageView.frame.size.width + 6, self.customView.goodImageView.frame.origin.y + 2, 0, 0)];
    [self.customView.goodLable sizeToFit];
    [self.customView.badImageView setFrame:CGRectMake(66, self.customView.goodImageView.frame.origin.y, 11, 16)];
    [self.customView.badLable setFrame:CGRectMake(24, self.customView.goodImageView.frame.origin.y + self.customView.contentView.frame.size.height, 0, 0)];
    self.customView.badLable.text = [NSString stringWithFormat:@"%ld",[self.model.bad longValue]];
    [self.customView.badLable setFrame:CGRectMake(self.customView.badImageView.frame.origin.x + self.customView.badImageView.frame.size.width + 6, self.customView.badImageView.frame.origin.y + 2, 0, 0)];
    [self.customView.badLable sizeToFit];
    
    // 重新设定headerView
    //    NSTimer * timer = [NSTimer timerWithTimeInterval:1.5 target:self selector:@selector(refreshView) userInfo:nil repeats:NO];
    //    [timer fire];
    [self.customView.tableHeaderView setFrame:CGRectMake(0, self.customView.badImageView.frame.origin.x + self.customView.badImageView.frame.size.width, SCREEN_WIDTH, self.customView.goodImageView.frame.origin.y + self.customView.goodImageView.frame.size.height + 5)];
    [self.customView.commentTabelView setTableHeaderView:self.customView.tableHeaderView];
    [self.customView.commentTabelView reloadData];
}

- (void)refreshView
{
    [self.customView.tableHeaderView setFrame:CGRectMake(0, self.customView.badImageView.frame.origin.x + self.customView.badImageView.frame.size.width, SCREEN_WIDTH, self.customView.goodImageView.frame.origin.y + self.customView.goodImageView.frame.size.height)];
    [self.customView.commentTabelView setTableHeaderView:self.customView.tableHeaderView];
    [self.customView.commentTabelView reloadData];
}
#pragma mark - tableView代理
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * infoDic = [self.dataArray objectAtIndex:indexPath.row];
    if ([[infoDic objectForKey:@"replytoId"] isEqualToString:@"-1"]) {
        DetailTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.infoDic = infoDic;
        [cell.replyButton setTitle:[NSString stringWithFormat:@"%@:", [infoDic objectForKey:@"puberNick"]] forState:UIControlStateNormal];
        [cell.timeLabel setText:[infoDic objectForKey:@"pubTime"]];
        
        return cell;
    }
    else {
        DetailReplyTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"detailReplyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.infoDic = infoDic;
        [cell.replyButton setTitle:[NSString stringWithFormat:@"%@:", [infoDic objectForKey:@"puberNick"]] forState:UIControlStateNormal];
        [cell.hostButton setTitle:[NSString stringWithFormat:@"%@:", [infoDic objectForKey:@"replytoNick"]] forState:UIControlStateNormal];
        [cell.replyLabel setText:[infoDic objectForKey:@"content"]];
        return cell;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray count];
    //        return [self.dataArray count] > 0 ? 1 : 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SETextView * view = [[SETextView alloc] init];
    NSString *text = [[_dataArray objectAtIndex:indexPath.row ] objectForKey:@"content"];    NSArray * resultArr = [FaceModel getImageByString:text];
    
    NSInteger count = [resultArr count];
    for (int i = count - 1; i >= 0; i --) {
        id element = [resultArr objectAtIndex:i];
        if ([element isKindOfClass:[NSAttributedString class]]) {
            [view insertAttributedText:element];
        }
        else if ([element isKindOfClass:[UIImage class]]) {
            EditImage * image = [[EditImage alloc] initWithData:UIImageJPEGRepresentation(element, 1.0)];
            image.name = @"123";
            [view insertObject:image size:CGSizeMake(35, 35)];
        }
    }
    
    UILabel * label = [[UILabel alloc] init];
    [label setText:[[_dataArray objectAtIndex:indexPath.row ] objectForKey:@"pubTime"]];
    [label sizeToFit];
    CGSize containerSize = CGSizeMake(SCREEN_WIDTH - label.frame.size.width, 10000);
    CGSize contentSize = [view sizeThatFits:containerSize];
    
    return  contentSize.height + 36 ;
    //    return 60;
}
- (void)detailReplyAction:(NSString *)userID
{
    //    NSLog(@"%@", userID);
    OtherPersonViewController *otherVC = [[OtherPersonViewController alloc] init];
    otherVC.puberId = userID;
    [self.navigationController pushViewController:otherVC animated:YES];
}
- (void)pushContent
{
    //构造分享内容
    self.publishContent = [ShareSDK content:self.model.content
                             defaultContent:self.model.content
                                      image:nil
                                      title:self.model.title
                                        url:@"http://www.isu.so"
                                description:@"喜欢豆号的欢迎下载"
                                  mediaType:SSPublishContentMediaTypeNews];
    
}


#pragma mark - tableView代理结束




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - aleart
- (void)aleareViewWithString:(NSString *)message
{
    UIAlertView *aleart = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [aleart show];
}
#pragma mark - 添加按钮点击事件
// 添加按钮点击事件
- (void)addButtonAction
{
    [self.customView.leftButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //赞
    [self.customView.supportButton addTarget:self action:@selector(supportButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //踩
    [self.customView.demeanButton addTarget:self action:@selector(demeanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 分享按钮
    [self.customView.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //朋友圈
    [self.customView.FriendCircleButton addTarget:self action:@selector(FriendCircleButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //微信
    [self.customView.weiXinButton addTarget:self action:@selector(weiXinButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //新浪
    [self.customView.XinLangButton addTarget:self action:@selector(XinLangButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //qq空间
    [self.customView.QQZineButton addTarget:self action:@selector(QQZineButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //qq好友
    [self.customView.QQButton addTarget:self action:@selector(QQButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    // 人人
    [self.customView.renrenButton addTarget:self action:@selector(renrenButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    //表情键盘
    [self.customView.senderButton addTarget:self action:@selector(senderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark -  -------分享-------
- (void)FriendCircleButtonAction:(id)sender
{
    [self pushContent];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:YES
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    
    [ShareSDK shareContent:self.publishContent type:ShareTypeWeixiTimeline authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:NO wxSessionButtonHidden:NO
                                                                                                                                wxTimelineButtonHidden:NO
                                                                                                                                  showKeyboardOnAppear:NO
                                                                                                                                     shareViewDelegate:nil
                                                                                                                                   friendsViewDelegate:nil
                                                                                                                                 picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
        
    }];
    
    
}
- (void)weiXinButtonAction:(id)sender
{
    [self pushContent];
    
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:nil authManagerViewDelegate:nil];
    [ShareSDK shareContent:self.publishContent type:ShareTypeWeixiSession authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:NO wxSessionButtonHidden:NO wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
        
    }];
    
}
- (void)XinLangButtonAction:(id)sender
{
    [self pushContent];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:nil authManagerViewDelegate:nil];
    [ShareSDK shareContent:self.publishContent type:ShareTypeSinaWeibo authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:NO wxSessionButtonHidden:NO wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
    }];
}
- (void)QQZineButtonAction:(id)sender
{
    [self pushContent];
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:nil authManagerViewDelegate:nil];
    [ShareSDK shareContent:self.publishContent type:ShareTypeQQSpace authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                          oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:YES wxSessionButtonHidden:NO wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
    }];
}
- (void)QQButtonAction:(id)sender
{
    [self pushContent];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:nil authManagerViewDelegate:nil];
    [ShareSDK shareContent:self.publishContent type:ShareTypeQQ authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:NO wxSessionButtonHidden:NO wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            //            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
    }];
}
- (void)renrenButtonAction:(id)sender
{
    [self pushContent];
    
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES allowCallback:YES authViewStyle:SSAuthViewStyleFullScreenPopup viewDelegate:nil authManagerViewDelegate:nil];
    [ShareSDK shareContent:self.publishContent type:ShareTypeRenren authOptions:authOptions shareOptions:[ShareSDK defaultShareOptionsWithTitle:nil                                                           oneKeyShareList:[NSArray defaultOneKeyShareList]qqButtonHidden:NO wxSessionButtonHidden:NO wxTimelineButtonHidden:NO showKeyboardOnAppear:NO shareViewDelegate:nil friendsViewDelegate:nil picViewerViewDelegate:nil]statusBarTips:YES result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSPublishContentStateSuccess)
        {
            //            NSLog(@"发表成功");
        }
        else if (state == SSPublishContentStateFail)
        {
            [self aleareViewWithString:[error errorDescription]];
        }
    }];
}


- (NSString *)puberNickChangeString:(NSString *)puberNick
{
    if  ([puberNick rangeOfString:@"s_user"].location != NSNotFound && [puberNick rangeOfString:@"_idt"].location != NSNotFound) {
        NSString *puberNick = [NSString stringWithFormat:@" • 学生用户 • 认证用户"];
        return puberNick;
    } else if  ([puberNick rangeOfString:@"t_user"].location != NSNotFound && [puberNick rangeOfString:@"_idt"].location != NSNotFound) {
        NSString *puberNick = [NSString stringWithFormat:@" • 教师用户 • 认证用户"];
        return puberNick;
    } else if  ([puberNick rangeOfString:@"s_user"].location != NSNotFound && [puberNick rangeOfString:@"_idt"].location == NSNotFound) {
        NSString *puberNick = [NSString stringWithFormat:@" • 学生用户 • 未认证用户"];
        return puberNick;
    } else if  ([puberNick rangeOfString:@"t_user"].location != NSNotFound && [puberNick rangeOfString:@"_idt"].location == NSNotFound) {
        NSString *puberNick = [NSString stringWithFormat:@" • 教师用户 • 未认证用户"];
        return puberNick;
    } else
    {
        return @"";
    }
}
@end
